package com.demo.servlet.servlets;

import com.demo.servlet.entity.CityInfoResponse;
import com.demo.servlet.entity.CityIspInfo;
import com.demo.servlet.entity.Response;
import com.demo.servlet.utils.FormatUtils;

import com.demo.servlet.utils.IpUtils;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.Inet4Address;
import java.net.InetAddress;

/**
 *  @ClassName: CityInforServlet
 *  * @Author: lizexin
 *  * @Description: Servlet类实现 得到ip 解析ip 返回ip地址
 *  * @Date: 2020/11/30 11:51
 *  * @Version: 1.0
 */
public class CityInforServlet extends HttpServlet {

    //Web客户向Servlet容器发出Http请求
    @Override /*处理get请求*/
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Response response = null;
        String getIp = IpUtils.LOCAL_IP; /*本机ip*/
        String hostName = IpUtils.HOST_NAME; /*hostname*/
        //String ip = IpUtils.getV4IP();
        String ip = IpUtils.getV4IP();

        System.out.println("本机IP:"+getIp);
        System.out.println("hostName: "+hostName);
        System.out.println("ipv4: " +ip);

        /*得到req中的参数*/
//       String ip = req.getParameter("ip");


        System.out.println("这个ip是: "+ip);
        /*判断参数中, ip格式等信息是否正确*/
        if (!FormatUtils.isIp(ip)){
            response = Response.failed("ip is wrong");
            FormatUtils.response(req,resp,response);
            return;
        }else{
     //Servlet容器解析Web客户的Http请求；
            /*根据ip获取到相应的城市*/
            CityIspInfo cityIspInfo = CityIspInfo.getCityInfo(ip);
            System.out.println("ip： "+ip);
            /*返回数据*/
            CityInfoResponse entity = new CityInfoResponse();
            entity.setCountryNmae(cityIspInfo.getCountryNmae());
            entity.setRegionName(cityIspInfo.getRegionName());
            entity.setCityName(cityIspInfo.getCityName());
            entity.setDistrictName(cityIspInfo.getDistrictName());

            response = Response.success();
            response.setBody(entity);
            FormatUtils.response(req,resp,response);
        }
    }



    @Override /*生成响应数据*/
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}